package cn.com.wxd.service.permissions.core;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.wxd.service.permissions.entity.FunctionPermissions;
import cn.com.wxd.service.permissions.entity.ModelPermissions;
import cn.com.wxd.service.permissions.entity.PermissionsEntity;

/**
 * Title:权限处理核心类
 * Description:对配置在xml中的数据进行复杂的处理和验证
 * 
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2016
 * All right reserved.
 * Created time: 2017-1-5 下午3:11:57
 *
 * @author WangXuDong
 * @version 2.0
 */
public class PermissionsCore {
	private static final String XMLFILEPATH = "user-permissions.xml";
	private static final Logger log = LoggerFactory.getLogger(PermissionsCore.class);
	private static Document document = null;
	private static List<PermissionsEntity> pes = null;
	private static PermissionsCore permissionsCore;
	private PermissionsCore() throws Exception{
		init();
		if(!checkData()){
			throw new Exception("权限配置文件生成数据校验错误!");
		}
	}
	public static PermissionsCore getInstance() throws Exception{
		if(permissionsCore==null){
			permissionsCore = new PermissionsCore();
			if(pes==null){
				throw new Exception("user-permissions.xml配置文件没有配置权限，无法解析！");
			}
		}
		return permissionsCore;
	}
	/**
	 * 从配置文件初始化并解析填充权限对象
	 * @throws Exception 
	 */
	private void init() throws Exception{
		//读取文件
		try {
			SAXReader reader = new SAXReader();
			InputStream inputStream = PermissionsCore.class.getClassLoader().getResourceAsStream(XMLFILEPATH);
			reader.setEncoding("UTF-8");
			document = reader.read(inputStream);
		} catch (Exception e) {
            log.error("读取xml文件路径配置文件错误！",e);
			throw e;
		}
		//准备解析文件填充的对象
		pes = new ArrayList<>();
		try {
			//解析文件节点并填充对象
			Element root = document.getRootElement();
			List nodes = root.elements("system-permi");  //解析系统所有权限
			for (Iterator it = nodes.iterator(); it.hasNext();) {
				Element elm = (Element) it.next();
				List modelPermiEles = elm.elements("model-permi");  //解析模块所有权限
				List<ModelPermissions> modelList = new ArrayList<>();
				if(modelPermiEles!=null){
					for (int i = 0; i < modelPermiEles.size(); i++) {
						//解析操作的权限
						Element modelEles = (Element)modelPermiEles.get(i);
						List functionPermiEls = modelEles.elements("function-permi");
						List<FunctionPermissions> functionList = new ArrayList<>();
						if(functionPermiEls!=null){
							for (int j = 0; j < functionPermiEls.size(); j++) {
								//填充操作权限
								Element functionEles = (Element)functionPermiEls.get(j);
								FunctionPermissions fp = new FunctionPermissions();
								fp.setCode(functionEles.getTextTrim());
								fp.setName(getAttributeByElement(functionEles,"name"));
								if(fp.getCode()!=null&&!fp.getCode().trim().equals("")){
									functionList.add(fp);
								}
							}
						}
						//填充模块权限
						ModelPermissions mp = new ModelPermissions();
						mp.setCode(getAttributeByElement(modelEles,"name"));
						mp.setName(getAttributeByElement(modelEles,"permi"));
						mp.setFunctionPermissions(functionList);
						if(mp.getCode()!=null&&!mp.getCode().trim().equals("")){
							modelList.add(mp);
						}
					}
				}
				//填充系统权限
				PermissionsEntity pe = new PermissionsEntity();
				pe.setCode(getAttributeByElement(elm,"name"));
				pe.setName(getAttributeByElement(elm,"permi"));
				pe.setModelPermissions(modelList);
				if(pe.getCode()!=null&&!pe.getCode().trim().equals("")){
					pes.add(pe);
				}
			}
		} catch (Exception e) {
            log.error("解析权限配置文件错误！"+e.getMessage(),e);
			throw e;
		}
		
	}
	/**
	 * 根据Element的属性名或子节点名称获取属性值，
	 * 如果该属性或节点不存在则返回空字符串
	 * 如果同时配置，属性优先级大于节点
	 * @return
	 */
	private String getAttributeByElement(Element element,String arrtibuteName){
		String value  = "";
		if(element==null){
			value = "";
		}
		List attrList = element.attributes();
		for (int i = 0; i < attrList.size(); i++) {
		    //属性的取得
		    Attribute item = (Attribute)attrList.get(i);
		    if(item!=null&&item.getName().equalsIgnoreCase(arrtibuteName)){
		    	value = item.getValue();
		    	return value;
		    } 
		}
		if(value==null||value.trim().equalsIgnoreCase("")){
			Element ele = element.element(arrtibuteName);
			if(ele!=null){
				value = ele.getTextTrim();
				if(value==null){
					value = "";
				}
			}
		}
		return value;
	}
	/**
	 * TODO 检查数据的正确性，即检查重复性和空配置
	 */
	private boolean checkData(){
		return true;
	}
	public List<PermissionsEntity> getAllPermissions(){
		return pes;
	}
}
